<?php

namespace App\Modules\LuckDraw\UserTag;

use App\Modules\LuckDraw\Models\DrawLogModel;

class ConsumptionPlusUserTag implements UserTagInterface {
    private $_luckId;
    private $_userId;
    private $_strategyPool;
    public function __construct(int $luckId, int $_userId, object $strategyPool) {
        $this->_luckId = $luckId;
        $this->_userId = $_userId;
        $this->_strategyPool = $strategyPool;
    }

    public function getStrategyPool():?array{
        if (empty($this->_strategyPool)) {
            return [];
        }
        //判断是不是走个人奖池
        $pd = $this->_getPersonal();
        if (!empty($pd)) {
            return [$pd->strategy, $pd->pool];
        }
        //获取用户消费信息
        $total = $this->_getConsumptionTotalWeek();
        foreach ($this->_strategyPool->common as $strategyPool) {
            if ($total >= $strategyPool->consumption_from && $total < $strategyPool->consumption_to) {
                return [$strategyPool->strategy, $strategyPool->pool];
            }
        }
        return [];
    }

    private function _getPersonal(){
        foreach ($this->_strategyPool->personal as $pd) {
            if (in_array($this->_userId, $pd->user_list)) {
                return $pd;
            }
        }
        return null;
    }

    //获取24小时内消费总额
    private function _getConsumptionTotalWeek(){
        return DrawLogModel::query()
            ->where("user_id", $this->_userId)
            ->where("luck_id", $this->_luckId)
            ->where("created_at", ">", date('Y-m-d', strtotime('this week')))
            ->sum("draw_num");
    }
    public function getStrategyAllPool():?array{
        if (empty($this->_strategyPool)) {
            return [];
        }
        $data = [];
        //判断是否有个人奖池
        if (isset($this->_strategyPool->personal)) {
            foreach ($this->_strategyPool->personal as $pd) {
                $data[] = [$pd->strategy, $pd->pool, $pd->user_list,'personal'];
            }
        }

        //获取用户消费信息
        if (isset($this->_strategyPool->common)) {
            foreach ($this->_strategyPool->common as $key => $strategyPool) {
                $data[] = [$strategyPool->strategy, $strategyPool->pool,[],'common'.'|'.$key];
            }
        }

        return $data;
    }

    public function getUpdatedUserTagByPoolData(array $newPool): ?array {
        $oldStrategyPool = $this->_strategyPool;
        //获取更改过的奖品信息
        $changedAwards = [];
        foreach ($newPool as $a){
            if (isset($a['old_data'])) {
                $keyOld = sprintf("%s-%s-%s",  $a['old_data']['type'], $a['old_data']['id'], $a['old_data']['time']);
                $keyNew = sprintf("%s-%s-%s",  $a['type'], $a['id'], $a['time']);
                if ($keyOld != $keyNew) {
                    $changedAwards[$keyOld] = $a;
                }
            }
        }

        $needUpdate = false;

        //主要是查看补偿的奖品有没有被改，有被修改的话就更新，没有就算了
        //普通
        if(isset($oldStrategyPool->common)){
            foreach ($oldStrategyPool->common as $pool) {
                if (isset($pool->strategy->ext->awards)) {
                    //对比当前id
                    foreach ($pool->strategy->ext->awards as $award) {
                        $key = sprintf("%s-%s-%s",  $award->type, $award->id, $award->time);
                        if (isset($changedAwards[$key])) {
                            $award->id = $changedAwards[$key]['id'];
                            $award->type = $changedAwards[$key]['type'];
                            $award->time = $changedAwards[$key]['time'];
                            $award->price = $changedAwards[$key]['price'];
                            $needUpdate = true;
                        }
                    }
                }
            }
        }

        //个人
        if(isset($oldStrategyPool->personal)){
            foreach ($oldStrategyPool->personal as $pool) {
                if (isset($pool->strategy->ext->awards)) {
                    //对比当前id
                    foreach ($pool->strategy->ext->awards as $award) {
                        $key = sprintf("%s-%s-%s",  $award->type, $award->id, $award->time);
                        if (isset($changedAwards[$key])) {
                            $award->id = $changedAwards[$key]['id'];
                            $award->type = $changedAwards[$key]['type'];
                            $award->time = $changedAwards[$key]['time'];
                            $award->price = $changedAwards[$key]['price'];
                            $needUpdate = true;
                        }
                    }
                }
            }
        }

        //注册
//        if(isset($oldStrategyPool->register)){
//            foreach ($oldStrategyPool->register as $pool) {
//                if (!empty($pool->strategy->ext)) {
//                    //对比当前id
//                    foreach ($pool->strategy->ext as $award) {
//                        $key = sprintf("%s-%s-%s",  $award->type, $award->id, $award->time);
//                        if (isset($changedAwards[$key])) {
//                            $award->id = $changedAwards[$key]['id'];
//                            $award->type = $changedAwards[$key]['type'];
//                            $award->time = $changedAwards[$key]['time'];
//                            $award->price = $changedAwards[$key]['price'];
//                        }
//                    }
//                }
//            }
//        }

        //返回修改后的数据
        return [$needUpdate, json_encode($oldStrategyPool)] ;
    }

    //获取所有策略的名字
    public function getAllStrategyAndUserIds(){
        //获取更改过的奖品信息
        $allStrategy = [];
        $userList = [];
        //普通
        if(isset($this->_strategyPool->common)){
            foreach ($this->_strategyPool->common as $pool) {
                if (isset($pool->strategy->name)) {
                    $allStrategy[$pool->strategy->name] = 1;
                }
            }
        }

        //个人 这个标签不循环
        if(isset($this->_strategyPool->personal)){
            foreach($this->_strategyPool->personal as $pool){
                if (isset($pool->strategy->name)) {
                    $allStrategy[$pool->strategy->name] = 1;
                }
                if (isset($pool->user_list)) {
                    $userList = array_merge($userList, $pool->user_list);
                }
            }
        }
        //注册 这个标签不循环
//        if(isset($this->_strategyPool->register)){
//            if (isset($this->_strategyPool->register->strategy->name)) {
//                $allStrategy[$this->_strategyPool->register->strategy->name] = 1;
//            }
//        }

        return [array_keys($allStrategy), $userList];
    }
}
